package com.tie.catalogo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.util.ArrayList;

import android.os.Environment;

public class Downloader {
	CatalogSelector parent;

	public Downloader() {

		File f = new File(Environment.getExternalStorageDirectory()
				+ "/catalog");
		if (!f.exists())
			f.mkdir();
		f = new File(Environment.getExternalStorageDirectory()
				+ "/catalog/images");
		if (!f.exists())
			f.mkdir();
	}

	public Downloader(CatalogSelector parent) {
		this.parent = parent;

		File f = new File(Environment.getExternalStorageDirectory()
				+ "/catalog");
		if (!f.exists())
			f.mkdir();
		f = new File(Environment.getExternalStorageDirectory()
				+ "/catalog/images");
		if (!f.exists())
			f.mkdir();
	}

	public void downloadAllImages(final ArrayList<String> urls) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int a = 0; a < urls.size(); a++) {
					downloadImage(urls.get(a));
				}
			}
		}).start();
	}

	public String downloadImage(final String url) {
		String name = "";
		try {
			for (int a = url.length(); a > 0; a--) {
				if (!Character.toString(url.charAt(a - 1)).equals("/")) {
					name = Character.toString(url.charAt(a - 1)) + name;
				} else {
					break;
				}
			}
			java.io.BufferedInputStream in = new java.io.BufferedInputStream(
					new java.net.URL(url).openStream());
			System.out.println("1");
			java.io.FileOutputStream fos = new java.io.FileOutputStream(
					Environment.getExternalStorageDirectory()
							+ "/catalog/images/" + name);
			System.out.println("2");
			java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,
					1024);
			System.out.println("3");
			byte[] data = new byte[1024];
			System.out.println("4");
			int x = 0;
			while ((x = in.read(data, 0, 1024)) >= 0) {
				bout.write(data, 0, x);
			}
			fos.flush();
			bout.flush();
			fos.close();
			bout.close();
			in.close();

		} catch (Exception e) {
			/* Display any Error to the GUI. */
			e.printStackTrace();
		}
		return name;
	}
}
